#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "featurepp.h"

/* parameters:
   argv[1] = Inputfile (CSV)
   argv[2] = Outputfile (CSV)
   argv[3] = Bitstring marking dimensions with 1 that shall be included
   */

main(int argc, char *argv[]) {

   FILE *fpsource, *fpoutput;

   if( argc != 4) {
      printf("usage: mask inputfile outputfile bitstring\n");
      exit(1);
   }

   char c;
  
   printf("Open: %s\n", argv[1]);
   if ((fpsource = fopen64((argv[1]), "r"))==NULL) {
      printf("error: can't open Sourcefile %s\n", *argv[1]);
      exit(1);
   }

      printf("Open: %s\n", argv[2]);
   if ((fpoutput = fopen64(argv[2], "w"))==NULL) {
      printf("error: can't create Outputfile %s\n", *argv[2]);
      exit(1);
   }
   
   printf("\nchecking mask...");
   checkmask(argv[3], fpsource);    /* primitive checking for wrong inputs */
   printf("okay.\n");
   
   rewind(fpsource);    // setting back filepointer
   
   printf("Masking Features...");
   maskFeatures(argv[3], fpsource, fpoutput);
   printf("done.\n");
   
   fclose(fpsource);
   fclose(fpoutput);
   return(0);
}

/* checkmask:  checks, whether mask and dimension of features fit */
int checkmask(char *s, FILE *fpsource) {
   
   char t[1000];      //Buffer
   
   int i = 1;
   int j;
   
   FILE *fp = fpsource;
   while(readArg(t, fp)!='\n')
      i++;
  
   for(j = 0; j < strlen(s); j++) {
      if (s[j]!='1' && s[j]!='0' && s[j]!='\n') {
         fprintf(stderr, "error: invalid character %c used for mask, use only 0 or 1!\n", s[j]);
         exit(1);
      }
   }

   if (strlen(s)!=i) {
      fprintf(stderr, "error: mask-dimension(%d) don't fit with feature-dimension(%d)!\n", strlen(s), i);
      exit(1);
   }
     
   return 1;
}

/* maskfeatures:  puts features marked with 0 off the input file 
   CAUTION: will probably fail if mask is not correct */
void maskFeatures(char *s, FILE *fpsource, FILE *fpoutput) {

   char t[1000];            //Buffer
   int c;
   int linebreak = -1;     
   int i = 0;

   while((c = readArg(t, fpsource)) != EOF) {
      if (s[i]=='1') {           //printing field
         if (linebreak==0)             //there was an argument printed in
            fputs(",", fpoutput);      //the same line before
         if (linebreak==1)             //argument is last one in the line
            fputs("\n", fpoutput);
         fputs(t, fpoutput);
         if (c == '\n') 
            linebreak = 1;
         else
            linebreak = 0;
      } else {                   //not printing, except linebreaks!
         if (c == '\n') {
            fputs("\n", fpoutput);
            linebreak = -1;   //there was a line break, but no argument printed
         }
      }         
      i++;
      if (c == '\n')
         i = 0;
   }
}
